<?php

namespace app\user\logic;

use app\common\exception\LogicException;
use app\model\FeedPlan;
use app\model\FourteenFeedPlan;

class CookBookLogic
{
    protected FourteenFeedPlan $model;
    protected int $factory_id;

    public function __construct()
    {
        $this->model = new FourteenFeedPlan();
        $this->factory_id = request()->user_info['factory_id'];
    }

    /**
     * @Description 下拉选择
     * @param array $param
     * @time 2024/03/26 11:10:26
     * @return array
     * @throws \think\db\exception\DbException
     * @author: zj
     */
    public function selectList(array $param)
    {
        $query = $this->model->field('out_id as id,name')
            ->where('factory_id', $this->factory_id)
            ->where('delete_time', $this->model::IS_DELETE_NO);
        if ($param['name']) {
            $query->where('name', 'like', '%' . $param['name'] . '%');
        }

        return $query->order('out_id DESC')
            ->paginate([
                'list_rows' => $param['page_size'],
                'page' => $param['page']
            ])
            ->toArray();
    }

    /**
     * @Description 饲料计划信息
     * @param int $id
     * @time 2024/03/26 15:52:38
     * @return array[]
     * @author: zj
     */
    public function getFeedInfo(int $id)
    {
        $fourteenFeedPlan = $this->model
            ->where('out_id', $id)
            ->where('factory_id', $this->factory_id)
            ->where('delete_time', $this->model::IS_DELETE_NO)
            ->value('day_id', []);
        if (!$fourteenFeedPlan) {
            throw new LogicException('食谱不存在');
        }

        $feedModel = new FeedPlan();

        $medicineInfo = [
            ['Id' => 0, 'Name' => '', 'Weight' => 0],
            ['Id' => 0, 'Name' => '', 'Weight' => 0],
            ['Id' => 0, 'Name' => '', 'Weight' => 0],
            ['Id' => 0, 'Name' => '', 'Weight' => 0],
        ];

        $data = [];

        if (!is_array($fourteenFeedPlan)) {
            $fourteenFeedPlan = json_decode($fourteenFeedPlan, true);
        }

        foreach ($fourteenFeedPlan as $feedPlan) {
            $plan = $feedModel->alias('fp')
                ->join('feed f', 'f.out_id = fp.feed_id', 'left')
                ->field('fp.out_id as id,f.name as feed,fp.feed_weight,fp.medicine_info,fp.water_rate')
                ->where('fp.out_id', $feedPlan)
                ->where('fp.factory_id', $this->factory_id)
                ->where('fp.delete_time', $this->model::IS_DELETE_NO)
                ->find();
            $data[] = [
                'id' => $plan['id'] ?? $feedPlan,
                'feed' => $plan['feed'] ?? '',
                'feed_weight' => $plan['feed_weight'] ?? 0,
                'medicine_info' => $plan['medicine_info'] ?? json_encode($medicineInfo),
                'water_rate' => $plan['water_rate'] ?? 0,
            ];
        }

        return $data;
    }

}